package com.firewolf.vue.service.impl;

import com.firewolf.vue.mapper.MenuMapper;
import com.firewolf.vue.pojo.Menu;
import com.firewolf.vue.pojo.MenuExample;
import com.firewolf.vue.service.MenuService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/3/4
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findAll() {
        return findMenusByParentId(0L, "顶级菜单");
    }

    private List<Menu> findMenusByParentId(Long parentId, String parentname) {
        MenuExample me = new MenuExample();
        me.createCriteria().andParentIdEqualTo(parentId);
        me.setOrderByClause("order_num asc");
        List<Menu> menus = menuMapper.selectByExample(me);
        for (Menu m : menus) {
            m.setParentname(parentname);
            m.setCreateTime(null);
            m.setLastUpdateTime(null);
            List<Menu> children = findMenusByParentId(m.getId(), m.getName());
            m.setChildren(children);
        }
        return menus;
    }

    @Override
    public void save(Menu menu) {
        if (menu.getId() == null) {
            menu.setDelFlag((byte) 0);
            menuMapper.insert(menu);
        } else {
            menuMapper.updateByPrimaryKeySelective(menu);
        }
    }

    @Override
    public List<Menu> findMenusByUserName(String username) {
        List<Menu> menus = this.findAll();
        List<Long> menuIds = menuMapper.findMenuIdsByUserName(username);
        removeMenus(menus, menuIds);
        return menus;
    }

    private void removeMenus(List<Menu> menus, List<Long> menuIds) {

        if (CollectionUtils.isEmpty(menus) || CollectionUtils.isEmpty(menuIds))
            return;
        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            Menu m = iterator.next();
            if (!menuIds.contains(m.getId())) {
                iterator.remove();
                continue;
            }
            List<Menu> children = m.getChildren();
            removeMenus(children, menuIds);
        }
    }
}


